<template>
  <div>
    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="50%"
      @close="setRightDialogClose"
    >
      <!-- 树形组件
                show-checkbox:显示复选框
                node-key:设置选中节点对应的值
                default-expand-all:是否默认展开所有节点
                :default-checked-keys 设置默认选中项的数组
                ref:设置引用 -->
      <el-tree
        empty-text="权限为空"
        :data="rightsList"
        show-checkbox
        node-key="Pid"
        ref="RightRolesRulesRef"
        :check-strictly="true"
        :default-checked-keys="defaultCheckedKeys"
        @check-change="RightsCheckChange"
        :props="treeProps"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 添加角色对话框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addRolesDialogFlag"
      width="40%"
      @close="addRolesDialogFlag = false"
    >
      <el-form :model="addRoles" :rules="addRolesRules" label-width="80px">
        <el-form-item label="角色名:" prop="Rname">
          <el-input v-model="addRoles.Rname"></el-input>
        </el-form-item>
        <el-form-item label="角色描述:" prop="Rdescribe">
          <el-input v-model="addRoles.Rdescribe"></el-input>
        </el-form-item>
      </el-form>
      <el-tree
        empty-text="权限为空"
        :data="rightsList"
        show-checkbox
        ref="addRolesRulesRef"
        node-key="Pid"
        :props="treeProps"
        @check-change="handleCheckChange"
        :check-strictly="true"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRolesDialogFlag = false">取 消</el-button>
        <el-button type="primary" @click="addRolesBtn">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 卡片视图区域 -->
    <el-card body-style="padding:10px">
      <!-- 搜索与添加区域 -->
      <el-row>
        <el-col :span="5">
          <el-input
            size="small"
            v-model="searchName"
            placeholder="请输入查找的名称"
          >
            <el-button
              slot="append"
              @click="searchNameBtn()"
              icon="el-icon-search"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="2">
          <el-button
            @click="addRolesDialogFlag = true"
            size="small"
            icon="el-icon-delete"
            type="primary"
            >添加角色</el-button
          >
        </el-col>
      </el-row>
    </el-card>
    <el-table :data="RolesList" border>
      <el-table-column type="expand">
        <template slot-scope="scope">
          <el-row
            :class="['bdbottom', i1 === 0 ? 'bdtop' : '']"
            border
            v-for="(item1, i1) in scope.row.permissionBeans"
            :key="item1.Pid"
          >
            <!-- 渲染一级权限 -->
            <el-col :span="5">
              <el-tag @close="handleClose(item1.Pname)">
                {{ item1.Pname }}
              </el-tag>
            </el-col>
            <!-- 渲染二，三级权限 -->
            <el-col :span="19">
              <!-- 通过for循环嵌套渲染二级权限 -->
              <el-row
                :class="[i2 === 0 ? '' : 'bdtop']"
                v-for="(item2, i2) in item1.firstChild"
                :key="item2.Pid"
              >
                <el-col :span="6">
                  <el-tag @close="handleClose(item2.Pname)" type="success">{{
                    item2.Pname
                  }}</el-tag>
                </el-col>
                <el-col :span="18">
                  <el-tag
                    @close="handleClose(item3.Pname)"
                    type="warning"
                    v-for="item3 in item2.children"
                    :key="item3.Pid"
                  >
                    {{ item3.Pname }}
                  </el-tag>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column type="index"></el-table-column>
      <el-table-column label="角色" prop="Rname"></el-table-column>
      <el-table-column label="角色状态" prop="Rstate">
        <template slot-scope="scope">
          <el-tag
            v-if="scope.row.Rstate === '审核通过'"
            size="mini"
            type="success"
            >审核通过</el-tag
          >
          <el-tag
            v-if="scope.row.Rstate === '待审核'"
            size="mini"
            type="warning"
            >待审核</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column label="角色描述" prop="Rdescribe"></el-table-column>
      <el-table-column label="操作" width="200px">
        <template slot-scope="scope">
          <el-button
            class="warning"
            size="mini"
            type="text"
            @click="showSetRightDialog(scope.row)"
            icon="el-icon-setting"
            >分配权限</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="paginationBlock" style="margin-top: 15px">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 15, 20, 25]"
        :page-size="pageSize"
        layout="total,sizes, prev, pager, next,jumper"
        :total="RolesList.length"
      >
      </el-pagination>
      <!-- <Pagination v-bind:total="RolesList.length"></Pagination> -->
    </div>
  </div>
</template>

<script>
// import Pagination from "../components/Pagination.vue";
export default {
  data() {
    return {
      paginationList: [], // 此数组会由getlivestockInfo()函数调用由RolesList[]数组提取的部分数据存入来控制页面显示数据条数
      RolesList: [],
      addRolesDialogFlag: false,
      currentPage: 1, //当前页码
      pageSize: 10, //每页的数据条数
      rightsList: [],
      //控制分配权限对话框的显示
      setRightDialogVisible: false,
      //树形控件的属性绑定对象
      treeProps: {
        //通过label设置树形节点文本展示authName
        label: "Pname",
        //设置通过children属性展示子节点信息
        children: "children",
      },
      //设置树形控件中默认选中的内容
      defKeys: [],
      searchName: "",
      addRoles: { Rname: "", Rdescribe: "" },
      addRolesRules: {
        Rname: [{ required: true, message: "角色名不能为空", trigger: "blur" }],
      },
      checkedNodes: [],
      defaultCheckedKeys: [],
      RightRolesRulesNodes: [],
      Riding: 0, //正在操作的角色id
    };
  },
  methods: {
    getlivestockInfo() {
      let that = this;
      that.$axios
        .post("http://localhost:8080/RolesServiceAll") //补上后台接口即可
        .then((res) => {
          // 请求成功
          that.RolesList = res.data;
          // console.log(res.data);
          // 获取页面数据后立马调用下面函数
          that.getPageData();
          return;
        })
        .catch((error) => {
          // 请求失败
          console.log("请求失败");
          console.log(error);
        });
    },
    getPermissionInfo() {
      let that = this;
      that.$axios
        .post("http://localhost:8080/PermsChildServletAll") //补上后台接口即可
        .then((res) => {
          // 请求成功
          that.rightsList = res.data;
          // that.rightsList = that.rightsList.filter((per) => {
          //   per.children = per.firstChild;
          //   return per.children;
          // });
          // 获取页面数据后立马调用下面函数
          that.getPageData();
          return;
        })
        .catch((error) => {
          // 请求失败
          console.log("请求失败");
          console.log(error);
        });
    },
    // 获取分页之后的数据
    getPageData() {
      let start = (this.currentPage - 1) * this.pageSize;
      let end = start + this.pageSize;
      this.paginationList = this.RolesList.slice(start, end);
    },
    // 每页条数改变时触发 选择一页显示多少行
    handleSizeChange(val) {
      this.pageSize = val;
      this.getPageData();
    },
    // 当前页改变时触发 跳转其他页
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getPageData();
    },
    // 打开分配权限模态窗
    async showSetRightDialog(event) {
      this.Riding = event.Rid;
      // 连接使用角色id获取角色id所拥有的权限
      this.$axios
        .get(`http://localhost:8080/GetPmsByRolesId?Rid=${this.Riding}`)
        .then((res) => {
          this.defaultCheckedKeys = [];
          for (let i of res.data) {
            this.defaultCheckedKeys.push(i.Pid);
          }
        })
        .catch((err) => {
          console.log(err);
        });
      this.setRightDialogVisible = true;
    },
    // 关闭分配权限模态窗
    setRightDialogClose() {
      this.setRightDialogVisible = false;
    },
    // 分配权限的提交按钮
    allotRights() {
      let that = this;
      console.log("点击了分配权限的确认按钮");
      let params = new URLSearchParams();
      params.append("Rid", this.Riding);
      params.append("checkedNodes", JSON.stringify(this.RightRolesRulesNodes));
      this.$axios
        .post("http://localhost:8080/updateRolesAndPermi", params)
        .then((res) => {
          this.$message({
            type: "success",
            message: res.data,
          });
          that.getlivestockInfo();
          that.getPageData();
        })
        .catch((err) => {
          console.log(err);
          console.log("请求失败");
        });
      that.setRightDialogVisible = false;
    },
    // 分配权限获取选中的值
    RightsCheckChange() {
      // 获取所有选中的节点
      this.RightRolesRulesNodes =
        this.$refs.RightRolesRulesRef.getCheckedNodes();
    },
    // 通过名字删除角色
    openDel(tag) {
      let Rname = tag.Rname;
      let that = this;
      that
        .$confirm("此操作将永久删除该条信息，是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
        .then(() => {
          let params = new URLSearchParams();
          params.append("Rname", Rname);
          that.$axios
            .post("http://localhost:8080/DelRolesInfo", params)
            .then((res) => {
              console.log(res.data);
              that.$message({
                type: "success",
                message: res.data,
              });
              that.getlivestockInfo();
              that.getPageData();
            })
            .catch((err) => {
              console.log(err);
            });
        })
        .catch(() => {
          that.$message({
            message: "已取消删除",
          });
        });
    },
    handleClose(permName) {
      console.log(permName);
    },
    // 点击添加角色确定按钮
    addRolesBtn() {
      let params = new URLSearchParams();
      params.append("Rname", this.addRoles.Rname);
      params.append("Rdescribe", this.addRoles.Rdescribe);
      params.append("checkedNodes", JSON.stringify(this.checkedNodes));
      this.$axios
        .post("http://localhost:8080/addRolesAndPermi", params)
        .then((res) => {
          this.$message({
            type: "success",
            message: res.data,
          });
          that.getlivestockInfo();
          that.getPageData();
        })
        .catch((err) => {
          console.log(err);
          console.log("请求失败");
        });
    },
    handleCheckChange() {
      // 获取所有选中的节点
      this.checkedNodes = this.$refs.addRolesRulesRef.getCheckedNodes();
      console.log(this.checkedNodes);
    },
    // 通过名字查询信息
    searchNameBtn() {
      if (this.searchName == "") {
        this.getlivestockInfo();
      } else {
        let that = this;
        that.$axios
          .get(
            `http://localhost:8080/RolesServiceSearchByName?searchName=${this.searchName}`
          ) //补上后台接口即可
          .then((res) => {
            // 请求成功
            that.RolesList = res.data;
            // console.log(res.data);
            // 获取页面数据后立马调用下面函数
            that.getPageData();
            return;
          })
          .catch((error) => {
            // 请求失败
            console.log("请求失败");
            console.log(error);
          });
      }
    },
  },
  mounted() {
    this.getlivestockInfo();
    this.getPermissionInfo();
  },
};
</script>

<style scoped>
@import "../../../assets/css/PublicStyle.css";
.el-card .el-col {
  margin-right: 8px;
}
.bdbottom {
  margin-top: 10px;
  border: 0.1px solid rgb(222, 219, 219);
  display: flex;
  display: -webkit-flex;
  align-items: center;
}

.bdtop {
  margin-top: 10px;
}

.bdbottom:first-child {
  margin-top: 0px;
}

.bdbottom > .el-col:last-child > .el-row {
  border-bottom: 0.1px solid rgb(222, 219, 219);
  padding: 10px 0;
}

.bdbottom > .el-col:last-child > .el-row:last-child {
  border: 0px;
}
</style>
